package de.webalpha.parking.controller;

import java.util.ArrayList;
import java.util.List;
import java.util.logging.Logger;

import javax.annotation.PostConstruct;
import javax.ejb.Stateful;
import javax.ejb.TransactionAttribute;
import javax.ejb.TransactionAttributeType;
import javax.ejb.TransactionManagement;
import javax.enterprise.event.Event;
import javax.enterprise.inject.Model;
import javax.enterprise.inject.Produces;
import javax.inject.Inject;
import javax.inject.Named;
import javax.persistence.EntityManager;

import de.webalpha.parking.model.Booking;
import de.webalpha.parking.model.ParkingLot;

@Stateful
@Model
public class BookingController {
	@Inject
	private Logger log;

	@Inject
	private EntityManager em;

	@Inject
	private Event<Booking> bookingEventSrc;

	private Booking newBooking;
	
	private List<ParkingLot> parkingLotList = new ArrayList();

	@Produces
	@Named
	public Booking getNewBooking() {
		return newBooking;
	}

	public void register() throws Exception {
		log.info("Registering new booking with id: " + newBooking.getId());
//		em.getTransaction().begin();
		em.persist(newBooking);
//		em.getTransaction().commit();
		
		bookingEventSrc.fire(newBooking);
		initNewBooking();
	}

	@PostConstruct
	public void initNewBooking() {
		newBooking = new Booking();
		
		/*parkingLotList = new ArrayList();
		parkingLotList.add(new ParkingLot(1L, "lot 1"));
		parkingLotList.add(new ParkingLot(2L, "lot 2"));
		parkingLotList.add(new ParkingLot(3L, "lot 3"));*/
	}
	
	@Produces
	@Named
	public List<ParkingLot> getParkingLotList() {
		log.info("Fetching the list of parking lot list");
		
		List<ParkingLot> parkingLotList = fetchFromDb();
		
		log.info("Retrieved " + parkingLotList.size() + " entities");
		
		return parkingLotList;
	}

	private List<ParkingLot> fetchFromDb() {
		List<ParkingLot> parkingLotList = em.createQuery("from ParkingLot", ParkingLot.class).getResultList();
		return parkingLotList;
	}
	
}
